package com.wuwei.elearning.utils;

import com.wuwei.elearning.websocket.WebSocketServer;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URI;
import java.net.URL;

@Service
public class TrayService {

    public static void setToolTip(String str) {
        TrayService.trayIcon.setToolTip(str);
    }

    private static TrayIcon trayIcon;

    @SneakyThrows
    public void initSystemTray() {
        if (SystemTray.isSupported()) {
            URL resource = this.getClass().getClassLoader().getResource("learn.png");
            ImageIcon imageIcon = new ImageIcon(resource, "photo");
            Image image = imageIcon.getImage();
            trayIcon = new TrayIcon(image);
            trayIcon.setImageAutoSize(true);
            trayIcon.setToolTip("e_learning系统");

            PopupMenu pm = new PopupMenu();
            MenuItem mi = new MenuItem("Exit");
            MenuItem mi2 = new MenuItem("Enter");

            ActionListener listener = new ActionListener() {
                @SneakyThrows
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (e.getActionCommand().equals("Exit")) {
                        System.exit(0);
                    } else if (e.getActionCommand().equals("Enter")) {
                        URI uri = new URI("http://localhost");
                        Desktop desktop = Desktop.getDesktop();
                        desktop.browse(uri);
                    }
                }
            };

            pm.add(mi2);
            pm.add(mi);
            mi.addActionListener(listener);
            mi2.addActionListener(listener);
            trayIcon.setPopupMenu(pm);

            trayIcon.addMouseListener(new MouseAdapter() {
                @SneakyThrows
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        URI uri = new URI("http://localhost");
                        Desktop desktop = Desktop.getDesktop();
                        desktop.browse(uri);
                    }
                }
            });

            // 添加 MouseMotionListener 来检测鼠标移动
            trayIcon.addMouseMotionListener(new MouseMotionAdapter() {
                @SneakyThrows
                @Override
                public void mouseMoved(MouseEvent e) {
                    // 这里可以定义当鼠标悬停时要执行的操作
                    WebSocketServer.sendPingToAll();
                    setToolTip("当前在线人数为："+ WebSocketServer.getOnlineCount()+"人。");
                }
            });

            SystemTray.getSystemTray().add(trayIcon);
        } else {
            System.out.println("系统不支持托盘");
        }
    }

    public TrayIcon getTrayIcon() {
        return trayIcon;
    }
}
